<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>数据模拟管理系统</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: #f5f5f5;
            padding: 20px;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            overflow: hidden;
        }

        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            text-align: center;
        }

        .header h1 {
            margin-bottom: 10px;
        }

        .stats {
            display: flex;
            justify-content: space-around;
            background: #f8f9fa;
            padding: 20px;
            border-bottom: 1px solid #e9ecef;
        }

        .stat-item {
            text-align: center;
        }

        .stat-number {
            font-size: 24px;
            font-weight: bold;
            color: #495057;
        }

        .stat-label {
            font-size: 14px;
            color: #6c757d;
            margin-top: 5px;
        }

        .controls {
            padding: 20px;
            border-bottom: 1px solid #e9ecef;
            display: flex;
            gap: 10px;
            align-items: center;
        }

        .btn {
            padding: 8px 16px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: background-color 0.3s;
        }

        .btn-primary { background: #007bff; color: white; }
        .btn-primary:hover { background: #0056b3; }
        
        .btn-success { background: #28a745; color: white; }
        .btn-success:hover { background: #1e7e34; }
        
        .btn-danger { background: #dc3545; color: white; }
        .btn-danger:hover { background: #c82333; }
        
        .btn-warning { background: #ffc107; color: #212529; }
        .btn-warning:hover { background: #e0a800; }
        
        .btn-info { background: #17a2b8; color: white; }
        .btn-info:hover { background: #138496; }

        .form-group {
            display: flex;
            gap: 10px;
            align-items: center;
        }

        .form-control {
            padding: 8px;
            border: 1px solid #ced4da;
            border-radius: 4px;
            font-size: 14px;
        }

        .task-table {
            width: 100%;
            border-collapse: collapse;
        }

        .task-table th,
        .task-table td {
            padding: 12px;
            text-align: left;
            border-bottom: 1px solid #e9ecef;
        }

        .task-table th {
            background: #f8f9fa;
            font-weight: 600;
            color: #495057;
        }

        .task-table tbody tr:hover {
            background: #f8f9fa;
        }

        .status-badge {
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: 500;
        }

        .status-running { background: #d4edda; color: #155724; }
        .status-stopped { background: #f8d7da; color: #721c24; }
        .status-created { background: #d1ecf1; color: #0c5460; }
        .status-error { background: #f5c6cb; color: #721c24; }

        .mode-badge {
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: 500;
        }

        .mode-normal { background: #d4edda; color: #155724; }
        .mode-abnormal { background: #fff3cd; color: #856404; }

        .actions {
            display: flex;
            gap: 5px;
        }

        .loading {
            text-align: center;
            padding: 40px;
            color: #6c757d;
        }

        .error {
            background: #f8d7da;
            color: #721c24;
            padding: 15px;
            border-radius: 4px;
            margin: 20px;
        }

        .success {
            background: #d4edda;
            color: #155724;
            padding: 15px;
            border-radius: 4px;
            margin: 20px;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>数据模拟管理系统</h1>
            <p>实时数据模拟与任务管理平台</p>
        </div>

        <div class="stats" id="stats">
            <div class="stat-item">
                <div class="stat-number" id="totalTasks">-</div>
                <div class="stat-label">总任务数</div>
            </div>
            <div class="stat-item">
                <div class="stat-number" id="runningTasks">-</div>
                <div class="stat-label">运行中</div>
            </div>
            <div class="stat-item">
                <div class="stat-number" id="stoppedTasks">-</div>
                <div class="stat-label">已停止</div>
            </div>
            <div class="stat-item">
                <div class="stat-number" id="errorTasks">-</div>
                <div class="stat-label">错误</div>
            </div>
        </div>

        <div class="controls">
            <div class="form-group">
                <label>模板:</label>
                <select id="templateSelect" class="form-control">
                    <option value="">选择模板...</option>
                </select>
                <input type="text" id="taskName" class="form-control" placeholder="任务名称">
                <button class="btn btn-primary" onclick="createTask()">创建任务</button>
            </div>
            <button class="btn btn-info" onclick="refreshTasks()">刷新</button>
            <button class="btn btn-success" onclick="startOpcuaServer()">启动OPC UA</button>
            <button class="btn btn-warning" onclick="stopOpcuaServer()">停止OPC UA</button>
        </div>

        <div id="messageArea"></div>

        <div id="taskTableContainer">
            <div class="loading">加载中...</div>
        </div>
    </div>

    <script>
        const API_BASE = '/api/simulation';
        let templates = [];
        let tasks = [];

        // 初始化
        document.addEventListener('DOMContentLoaded', function() {
            loadTemplates();
            loadTasks();
            loadStatistics();
            
            // 定时刷新数据
            setInterval(() => {
                loadTasks();
                loadStatistics();
            }, 5000);
        });

        async function loadTemplates() {
            try {
                const response = await fetch(`${API_BASE}/templates`);
                templates = await response.json();
                
                const select = document.getElementById('templateSelect');
                select.innerHTML = '<option value="">选择模板...</option>';
                
                templates.forEach(template => {
                    const option = document.createElement('option');
                    option.value = template.templateId;
                    option.textContent = template.templateName;
                    select.appendChild(option);
                });
            } catch (error) {
                showMessage('加载模板失败: ' + error.message, 'error');
            }
        }

        async function loadTasks() {
            try {
                const response = await fetch(`${API_BASE}/tasks`);
                tasks = await response.json();
                renderTaskTable();
            } catch (error) {
                showMessage('加载任务失败: ' + error.message, 'error');
            }
        }

        async function loadStatistics() {
            try {
                const response = await fetch(`${API_BASE}/statistics`);
                const stats = await response.json();
                
                document.getElementById('totalTasks').textContent = stats.totalTasks || 0;
                document.getElementById('runningTasks').textContent = stats.runningTasks || 0;
                document.getElementById('stoppedTasks').textContent = stats.stoppedTasks || 0;
                document.getElementById('errorTasks').textContent = stats.errorTasks || 0;
            } catch (error) {
                console.error('加载统计信息失败:', error);
            }
        }

        function renderTaskTable() {
            const container = document.getElementById('taskTableContainer');
            
            if (tasks.length === 0) {
                container.innerHTML = '<div class="loading">暂无任务</div>';
                return;
            }

            const table = `
                <table class="task-table">
                    <thead>
                        <tr>
                            <th>任务名称</th>
                            <th>模板</th>
                            <th>状态</th>
                            <th>模式</th>
                            <th>运行时间</th>
                            <th>最后更新</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        ${tasks.map(task => `
                            <tr>
                                <td>${task.taskName}</td>
                                <td>${task.template?.templateName || task.templateId}</td>
                                <td><span class="status-badge status-${task.status.toLowerCase()}">${getStatusText(task.status)}</span></td>
                                <td><span class="mode-badge mode-${task.mode.toLowerCase()}">${getModeText(task.mode)}</span></td>
                                <td>${formatDuration(task.runDuration)}</td>
                                <td>${formatTime(task.lastUpdateTime)}</td>
                                <td>
                                    <div class="actions">
                                        ${task.status === 'RUNNING' ? 
                                            `<button class="btn btn-warning" onclick="stopTask('${task.taskId}')">停止</button>` :
                                            `<button class="btn btn-success" onclick="startTask('${task.taskId}')">启动</button>`
                                        }
                                        <button class="btn btn-info" onclick="toggleMode('${task.taskId}')">${task.mode === 'NORMAL' ? '异常' : '正常'}</button>
                                        <button class="btn btn-danger" onclick="deleteTask('${task.taskId}')">删除</button>
                                    </div>
                                </td>
                            </tr>
                        `).join('')}
                    </tbody>
                </table>
            `;
            
            container.innerHTML = table;
        }

        async function createTask() {
            const templateId = document.getElementById('templateSelect').value;
            const taskName = document.getElementById('taskName').value;
            
            if (!templateId || !taskName) {
                showMessage('请选择模板并输入任务名称', 'error');
                return;
            }

            try {
                const response = await fetch(`${API_BASE}/tasks`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ templateId, taskName })
                });
                
                const result = await response.json();
                
                if (result.success) {
                    showMessage('任务创建成功', 'success');
                    document.getElementById('taskName').value = '';
                    loadTasks();
                    loadStatistics();
                } else {
                    showMessage('任务创建失败: ' + result.message, 'error');
                }
            } catch (error) {
                showMessage('任务创建失败: ' + error.message, 'error');
            }
        }

        async function startTask(taskId) {
            try {
                const response = await fetch(`${API_BASE}/tasks/${taskId}/start`, { method: 'POST' });
                const result = await response.json();
                
                if (result.success) {
                    showMessage('任务启动成功', 'success');
                    loadTasks();
                    loadStatistics();
                } else {
                    showMessage('任务启动失败: ' + result.message, 'error');
                }
            } catch (error) {
                showMessage('任务启动失败: ' + error.message, 'error');
            }
        }

        async function stopTask(taskId) {
            try {
                const response = await fetch(`${API_BASE}/tasks/${taskId}/stop`, { method: 'POST' });
                const result = await response.json();
                
                if (result.success) {
                    showMessage('任务停止成功', 'success');
                    loadTasks();
                    loadStatistics();
                } else {
                    showMessage('任务停止失败: ' + result.message, 'error');
                }
            } catch (error) {
                showMessage('任务停止失败: ' + error.message, 'error');
            }
        }

        async function deleteTask(taskId) {
            if (!confirm('确定要删除这个任务吗？')) {
                return;
            }

            try {
                const response = await fetch(`${API_BASE}/tasks/${taskId}`, { method: 'DELETE' });
                const result = await response.json();
                
                if (result.success) {
                    showMessage('任务删除成功', 'success');
                    loadTasks();
                    loadStatistics();
                } else {
                    showMessage('任务删除失败: ' + result.message, 'error');
                }
            } catch (error) {
                showMessage('任务删除失败: ' + error.message, 'error');
            }
        }

        async function toggleMode(taskId) {
            try {
                const response = await fetch(`${API_BASE}/tasks/${taskId}/toggle-mode`, { method: 'POST' });
                const result = await response.json();
                
                if (result.success) {
                    showMessage(`模式切换为: ${getModeText(result.currentMode)}`, 'success');
                    loadTasks();
                } else {
                    showMessage('模式切换失败: ' + result.message, 'error');
                }
            } catch (error) {
                showMessage('模式切换失败: ' + error.message, 'error');
            }
        }

        async function startOpcuaServer() {
            try {
                const response = await fetch(`${API_BASE}/opcua/start`, { method: 'POST' });
                const result = await response.json();
                
                if (result.success) {
                    showMessage('OPC UA服务器启动成功', 'success');
                } else {
                    showMessage('OPC UA服务器启动失败: ' + result.message, 'error');
                }
            } catch (error) {
                showMessage('OPC UA服务器启动失败: ' + error.message, 'error');
            }
        }

        async function stopOpcuaServer() {
            try {
                const response = await fetch(`${API_BASE}/opcua/stop`, { method: 'POST' });
                const result = await response.json();
                
                if (result.success) {
                    showMessage('OPC UA服务器停止成功', 'success');
                } else {
                    showMessage('OPC UA服务器停止失败: ' + result.message, 'error');
                }
            } catch (error) {
                showMessage('OPC UA服务器停止失败: ' + error.message, 'error');
            }
        }

        function refreshTasks() {
            loadTasks();
            loadStatistics();
            showMessage('数据已刷新', 'success');
        }

        function showMessage(message, type) {
            const messageArea = document.getElementById('messageArea');
            messageArea.innerHTML = `<div class="${type}">${message}</div>`;
            
            setTimeout(() => {
                messageArea.innerHTML = '';
            }, 3000);
        }

        function getStatusText(status) {
            const statusMap = {
                'CREATED': '已创建',
                'RUNNING': '运行中',
                'STOPPED': '已停止',
                'ERROR': '错误',
                'PAUSED': '暂停'
            };
            return statusMap[status] || status;
        }

        function getModeText(mode) {
            const modeMap = {
                'NORMAL': '正常',
                'ABNORMAL': '异常'
            };
            return modeMap[mode] || mode;
        }

        function formatDuration(milliseconds) {
            if (!milliseconds || milliseconds === 0) return '-';
            
            const seconds = Math.floor(milliseconds / 1000);
            const hours = Math.floor(seconds / 3600);
            const minutes = Math.floor((seconds % 3600) / 60);
            const secs = seconds % 60;
            
            if (hours > 0) {
                return `${hours}h ${minutes}m ${secs}s`;
            } else if (minutes > 0) {
                return `${minutes}m ${secs}s`;
            } else {
                return `${secs}s`;
            }
        }

        function formatTime(timeString) {
            if (!timeString) return '-';
            
            const date = new Date(timeString);
            return date.toLocaleString('zh-CN');
        }
    </script>
</body>
</html> 